import axios from 'axios'
import store from '../vuex/store'
import router from '../router'
import {
  Message
} from 'element-ui';
//当创建实例的时候配置默认配置
var http = axios.create({
  baseURL: 'http://175.102.18.118:12311',
  // baseURL: 'http://192.168.1.28:8000',
  // baseURL: '/api',
  transformRequest: [function (data) {
    // 将数据转换为表单数据
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
  }],
});
http.defaults.withCredentials = true

// http request 拦截器
http.interceptors.request.use(
  config => {
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    let regex = /.*csrftoken=([^;.]*).*$/; // 用于从cookie中匹配 csrftoken值
    config.headers['X-CSRFToken'] = document.cookie.match(regex) === null ? null : document.cookie.match(regex)[1];
    // if (store.state.token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
    //   config.headers.Authorization = `token ${store.state.token}`;
 
    // }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

// http response 拦截器
http.interceptors.response.use(
  response => {
    return response;
  },
  errors => {
    console.log(errors.response)
    if (errors.response) {
      switch (errors.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          Message.warning(errors.response.data.detail)
          //   store.commit(types.LOGOUT);
          router.replace({
            path: '/login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
          break;
        case 400:
        let mess = ""
        for(let key in errors.response.data){
          console.log( errors.response.data[key])
          mess = key + errors.response.data[key][0]
        }
          Message.error(mess)
          break;
        default:
          Message.error(errors.response.data)
      }

    }
    return Promise.reject(errors.response.data) // 返回接口返回的错误信息
  });
export default http
